package com.lkm.app_ui.ui.fj;

import android.annotation.TargetApi;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.google.gson.JsonParser;
import com.google.gson.annotations.SerializedName;
import com.google.gson.reflect.TypeToken;
import com.lkm.app_ui.AppConst;
import com.lkm.app_ui.MBaseFragment;
import com.lkm.app_ui.R;
import com.lkm.app_ui.RouterUINavigation;
import com.lkm.app_ui.RunTimeData;
import com.lkm.app_ui.help.AppUIHelp;
import com.lkm.app_ui.help.HandleDialog;
import com.lkm.app_ui.m.fun.FunItem;
import com.lkm.app_ui.m.fun.OnKeyNumberEvent;
import com.lkm.app_ui.netapi.AppApi;
import com.lkm.app_ui.ui.fj.to.FjOrderItemTo;
import com.lkm.app_ui.ui.fj.to.FjOrderTo;
import com.lkm.app_ui.ui.sale.SaleUIFragment;
import com.lkm.app_ui.view.choiceCard.ChoiceCard;
import com.lkm.app_ui.view.choiceCard.ChoiceItem;
import com.lkm.app_ui.view.choiceCard.IChoiceItem;
import com.lkm.comlib.help.ViewHelp;
import com.lkm.comlib.help.ViewUIHelp;
import com.lkm.comlib.task2.DefaultTaskExecutor;
import com.lkm.comlib.ui.BaseFragmentActivity;
import com.lkm.comlib.ui.BaseHoldAdapter;
import com.lkm.comlib.ui.IHoldView;
import com.lkm.frame.otto.LinkBus;
import com.lkm.frame.otto.LinkBusCycleWrapper;
import com.lkm.frame.otto.ObserverAutoNext;
import com.lkm.frame.task2.TaskAdapter;
import com.lkm.frame.util.CycleHelp;
import com.lkm.javatool.CollectionHelp;
import com.lkm.javatool.JsonP1;
import com.lkm.javatool.NumberHelp;
import com.lkm.javatool.StringHelp;
import com.lkm.market2_0.entity.ResponEntity;
import com.lkm.market2_0.help.SteelardHelp;
import com.lkm.market2_0.m.steelyardserver.OnSteelyardKeyEvent;

import java.util.ArrayList;
import java.util.List;



public class FjOrderFragment extends MBaseFragment {

    

    public static FjOrderFragment getInstance(boolean exitFj_ls) {
        FjOrderFragment f = new FjOrderFragment();
        Bundle data = new Bundle();
        data.putBoolean("exitFj_ls", exitFj_ls);
        f.setArguments(data);
        return f;
    }

    
    FjInfo fjInfo = FjApp.install.getFjInfo();
    FjOrder fjOrder = null;

    

    boolean isRealNoFjOrder;

    

    private int curFocusIndex = FocusIndex_item;

    private static int FocusIndex_item = 1;
    private static int FocusIndex_fun = 2;

    private ItemsView itemsView;
    private FunView funView;

    @Override
    protected int configLayoutResID() {
        return R.layout.fj_fragment_order;
    }

    @Override
    protected boolean configIsLockKey() {
        return true;
    }

    TextView tv_order_info;

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        tv_order_info = ((TextView) findViewById(R.id.tv_order_info));
        itemsView = new ItemsView();
        funView = new FunView();
        binfjInfo();

        if(getArguments().getBoolean("exitFj_ls")){
            view.post(()->exitFj_ls());
        }
    }

    

    private void reShow() {

        if (fjOrder != null) {
            lastOrderNo = fjOrder.fjInfoNo;
            List<FjOrder.FjItem> souceList = fjOrder.fjItems;

//            for (FjOrder.FjItem item : fjOrder.fjItems) {
//                if (!StringHelp.isEmpty(item.realWeight)) {



            itemsView.setSouceList(souceList);
            tv_order_info.setText(Html.fromHtml(
                    "订单号：<font color='red' size='30px'> <big>" + fjOrder.fjInfoNo + "</big></font>" +
                            "   ；   日期：<font color='red' size='30px'> <big>" + fjOrder.createTime + "</big></font>" +
                            "   ；   挂起订单数：<font color='red' size='30px'> <big>" + FjApp.install.getFjWaitOrder().getSize() + "</big></font>单"
                    )
            );
        }

    }

    private void upFocusIndex(int FocusIndex) {
        curFocusIndex = FocusIndex;
        
        findViewById(R.id.v_focues_2).setVisibility(curFocusIndex == FocusIndex_fun ? View.VISIBLE : View.GONE);
    }

    

    private void binfjInfo() {
        LinkBusCycleWrapper.register(new ObserverAutoNext<OnFjInfoEvent>() {

            @Override
            public void onReceiver(OnFjInfoEvent data) {
                fjInfo = FjApp.install.getFjInfo();
                fjOrder = fjInfo == null ? null : fjInfo.getCurFjOrder();
                if (fjOrder == null) {


                    
                    if (isRealNoFjOrder) return;
                    holdTaskCollection().cancelAllTask();
                    // 当前没有在分拣的.那就要请求加载.
                    LoadFjOrderTask task = new LoadFjOrderTask();
                    task.action();
                    holdTaskCollection().add(task.execTask());
                } else {
                    reShow();
                }
            }

            @Override
            public Class<OnFjInfoEvent> getBusEventClass() {
                return OnFjInfoEvent.class;
            }
        }, holdCycleHelp(), CycleHelp.CycleType.Destroy);
    }


    private class ItemsView {
        private ListView listView;
        private MAdapter adapter;
        private List<FjOrder.FjItem> souceList = new ArrayList<>();

        public void setSouceList(List<FjOrder.FjItem> souceList) {
            this.souceList = souceList;
            adapter.notifyDataSetChanged();
        }

        public ItemsView() {
            ((TextView) findViewById(R.id.tv_weight_unit_title)).setText("重量(" + RunTimeData.getAppWeightUnit() + ")");
            listView = findViewById(R.id.vg_list).findViewById(android.R.id.list);
            listView.setAdapter(adapter = new MAdapter());

            reOnKeyNumberEvent();
        }

        private void reOnKeyNumberEvent() {

            LinkBusCycleWrapper.register(new ObserverAutoNext<OnKeyNumberEvent>() {
                @Override
                public Class<OnKeyNumberEvent> getBusEventClass() {
                    return OnKeyNumberEvent.class;
                }

                boolean isOnce = false;

                @Override
                public void onReceiver(OnKeyNumberEvent data) {
                    if (data.isIntercepted()) {
                        return;
                    }
                    if (!isOnce && data.isFinally()) {
                        
                        isOnce = true;
                        return;
                    }
                    isOnce = true;
                    if (!data.isFinally() && FjOrderFragment.this.isExit()) {
                        
                        LinkBus.unregisterReceiver(this);
                        return;
                    }
                    if (curFocusIndex != FocusIndex_item) return;
                    data.setIntercepted(true);

                    if (fjOrder == null) return;

                    
                    if (CollectionHelp.getSize(fjOrder.fjItems) < 10) {
                        if (!data.isFinally()) {
                            selectIetm((int) data.getNumber());
                        }
                    } else if (data.isFinally()) {
                        selectIetm((int) data.getNumber());
                    }
                }
            }, holdCycleHelp(), CycleHelp.CycleType.Destroy);

        }

        private void selectIetm(int index) {
            FjOrder.FjItem fjItem = fjOrder.getByIndex(index);
            if (fjItem == null) {
                AppUIHelp.tryShowTipsSHORT("输入的商品序号错误");
                return;
            }
            fjInfo.setCurFj(fjOrder, fjItem);
            RouterUINavigation.getInstance().dismiss(FjOrderFragment.this);
        }

        private class MAdapter extends BaseHoldAdapter {
            public MAdapter() {
                super(holdCycleHelp());
            }

            @Override
            public void notifyDataSetChanged() {
                super.notifyDataSetChanged();

            }

            @Override
            public IHoldView createHoldView(int position, View convertView, ViewGroup parent) {
                return new MHoldView();
            }

            @Override
            public int getCount() {
                return CollectionHelp.getSize(souceList);
            }

            @Override
            public Object getItem(int position) {
                return souceList.get(position);
            }
        }

        private class MHoldView extends LinearLayout implements IHoldView<FjOrder.FjItem> {

            private TextView tv_name, tv_price_unit, tv_weight, tv_totalPrice, tv_no;

            public MHoldView() {
                super(getActivity());
                ViewHelp.inflate(getActivity(), R.layout.item_sales, this);
                tv_no = (TextView) this.findViewById(R.id.tv_no);
                tv_name = (TextView) this.findViewById(R.id.tv_name);
                tv_price_unit = (TextView) this.findViewById(R.id.tv_price_unit);
                tv_weight = (TextView) this.findViewById(R.id.tv_weight);
                tv_totalPrice = (TextView) this.findViewById(R.id.tv_totalPrice);

            }

            private int position;

            @TargetApi(Build.VERSION_CODES.M)
            @Override
            public Object binData(FjOrder.FjItem obj, int position, boolean isonPause) {
                this.position = position;


                setBackgroundColor(position % 2 == 1 ? Color.YELLOW : Color.TRANSPARENT);
                tv_no.setText("" + (position));
                tv_name.setText(obj.goodsName);
                tv_price_unit.setText(SteelardHelp.formatMoney(obj.price));
//                tv_weight.setText(NumberHelp.formatMoney(obj.weight, 3, "--"));
                tv_weight.setText(obj.weight);

                tv_totalPrice.setText(obj.realWeight);

                setTag(obj);
                return null;
            }

        }   

    }

    private class FunView implements ChoiceCard.ChoiceCardBC {

        private ChoiceCard mChoiceCard;

        public FunView() {

            mChoiceCard = findViewById(R.id.ChoiceCard);
            mChoiceCard.setItemViewHeigth(ViewHelp.getPX(getActivity(), R.dimen.dp100px));
            mChoiceCard.init(false, R.layout.view_choice_card, R.layout.item, R.layout.item, 1);

            mChoiceCard.setChoiceCardBC(this);
            initDatax();
            reOnKeyEvent();
        }

        private void initDatax() {
            List<FunItem> funItems = new ArrayList<>();
            funItems.add(new FunItem("" + OnSteelyardKeyEvent.KEYCODE_0, "挂起当前订单", false));

            funItems.add(new FunItem("" + OnSteelyardKeyEvent.KEYCODE_1, "查看挂起订单", false));
            
            funItems.add(new FunItem("" + OnSteelyardKeyEvent.KEYCODE_2, "退出分拣", false));
            funItems.add(new FunItem("" + OnSteelyardKeyEvent.KEYCODE_3, "功能选择", false));



            funItems.add(new FunItem("" + OnSteelyardKeyEvent.KEYCODE_9, "退出"));

            ChoiceItem[] cis = new ChoiceItem[funItems.size()];
            int i = 0;
            for (FunItem funItem : funItems) {
                cis[i] = new ChoiceItem(funItem.id, funItem.id + "：" + funItem.name);
                cis[i].setTag(funItem);
                cis[i].setIsChoice(funItem.isChoice);
                i++;
            }

            mChoiceCard.binData(cis);
        }

        private void clickItem(int keyCode) {
            boolean hasItemFun = false;
            IChoiceItem[] items = mChoiceCard.getData();
            for (IChoiceItem item : items) {
                FunItem funItem = (FunItem) item.getTag();
                if (NumberHelp.toInt(funItem.id, -1) == keyCode) {
                    hasItemFun = true;
                    break;
                }
            }
            if (!hasItemFun) return;

            switch (keyCode) {
                case OnSteelyardKeyEvent.KEYCODE_0:
                    FjApp.install.waitOrder();
                    break;
                case OnSteelyardKeyEvent.KEYCODE_1: {
                    if (FjApp.install.getFjWaitOrder().getSize() < 1) {
                        AppUIHelp.tryShowTipsSHORT("暂无挂起订单");
                        return;
                    }
                    RouterUINavigation.getInstance().dismiss(FjOrderFragment.this);
                    RouterUINavigation.getInstance().showFjWaitOrder((BaseFragmentActivity) getActivity());
                }
                break;
                case OnSteelyardKeyEvent.KEYCODE_2:
                    exitFj_ls();

                    break;
                case OnSteelyardKeyEvent.KEYCODE_3: {
                    
                    RouterUINavigation.getInstance().showSaleFun((BaseFragmentActivity) getActivity(), FjOrderFragment.this, 0);
                    RouterUINavigation.getInstance().dismiss(FjOrderFragment.this);
                }
                break;
                case OnSteelyardKeyEvent.KEYCODE_9: {
                    RouterUINavigation.getInstance().dismiss(FjOrderFragment.this);
                }
                break;
            }

        }

        @Override
        public void onChoiceChangeListener(ChoiceCard cc, IChoiceItem c, int index) {
            if (c.getIsChoice()) {
                FunItem funItem = (FunItem) c.getTag();
                clickItem(NumberHelp.toInt(funItem.id, -1));
            }

        }

        
        private void reOnKeyEvent() {
            LinkBusCycleWrapper.register(new ObserverAutoNext<OnSteelyardKeyEvent>() {
                @Override
                public Class<OnSteelyardKeyEvent> getBusEventClass() {
                    return OnSteelyardKeyEvent.class;
                }

                @Override
                public void onReceiver(OnSteelyardKeyEvent data) {
                    if (!data.isIntercepted()) {
                        data.setIntercepted(true);

                        if(data.getKeyCode() == OnSteelyardKeyEvent.KEYCODE_FJ){
                            
                            RouterUINavigation.getInstance().dismiss(FjOrderFragment.this);
                            return;
                        }

                        if (curFocusIndex != FocusIndex_fun) {
                            if (data.getKeyCode() == OnSteelyardKeyEvent.KEYCODE_FUN)
                                upFocusIndex(FocusIndex_fun);
                            return;
                        }
                        if (data.getKeyCode() == OnSteelyardKeyEvent.KEYCODE_FUN) {
                            
                            RouterUINavigation.getInstance().dismiss(FjOrderFragment.this);
                        } else {
                            clickItem(data.getKeyCode());
                        }

                    }
                }
            }, holdCycleHelp(), CycleHelp.CycleType.Destroy);
        }


    }

    

    private void exitFj_ls(){

        RouterUINavigation.getInstance().dismiss(FjOrderFragment.this);
        AppConst.mainHandler.post(() -> {
            lsOrderNo = fjOrder == null ? "" : fjOrder.fjInfoNo;
            FjApp.install.waitOrder();
        });
    }


    
    private static String lsOrderNo = null;
    
    private String lastOrderNo = null;

    

    private class LoadFjOrderTask extends TaskAdapter<Void, Void, ResponEntity<FjOrder>> {

        public LoadFjOrderTask() {
            super(new DefaultTaskExecutor(AppConst.getTaskExecutor(), true), LoadFjOrderTask.class.getName(), AppConst.getTaskManager2());
        }

        @Override
        public void onPreExecute() {
            super.onPreExecute();
            ViewUIHelp.showProgressBar(getActivity(), "分拣订单-联网加载中", getId());
        }

        @Override
        public void doExecuting(Void param) {
            super.doExecuting(param);

            mTaskExecutor.executor(() -> {
                extracted();
            });
        }

        private void extracted() {
            FjOrder fjOrder = StringHelp.isEmpty(lsOrderNo) ? null : FjApp.install.getFjWaitOrder().popWaitOrder(lsOrderNo, null);

            lsOrderNo = null;
            
            if (fjOrder == null) {


                String json = AppApi.fjGet(LoadFjOrderTask.this);
                ResponEntity<List<FjOrderTo>> ree = ResponEntity.fromJson(json, new TypeToken<ArrayList<FjOrderTo>>() {
                }.getType(), "");
                if (ree.isSuccess()) {
                    ree.setMsg("");
                }

                ResponEntity<FjOrder> re = new ResponEntity<>(ree);
                FjOrderTo fjOrderTo = null;

                List<FjOrderTo> fjOrderTos = ree.getData();
                

                if (fjOrderTos != null) {
                    for (FjOrderTo orderTo : fjOrderTos) {
                        if (!FjApp.install.getFjWaitOrder().hasOrder(orderTo.order_no)) {
                            fjOrderTo = orderTo;
                            break;
                        }
                    }

                    
                    if (fjOrderTo == null) {
                        boolean lastOrderNoOK = false;
                        
                        for (FjOrderTo orderTo : fjOrderTos) {
                            if (StringHelp.equals(lastOrderNo, orderTo.order_no)) {
                                lastOrderNoOK = true;
                                continue;
                            }
                            if (!lastOrderNoOK) continue;

                            if (FjApp.install.getFjWaitOrder().hasOrder(orderTo.order_no)) {
                                fjOrderTo = orderTo;// FjApp.install.getFjWaitOrder().popWaitOrder(orderTo.order_no,null);
                                break;
                            }
                        }
                        
                        if (fjOrderTo == null)
                            fjOrderTo = CollectionHelp.getFirst(fjOrderTos);
                        if (fjOrderTo != null)
                            re.setMsg("挂起订单已过多，请优先处理");
                    }
                }


                // CollectionHelp.getFirst(ree.getData());
                if (fjOrderTo == null)
                    re.fail(re.getMsg());
                if (re.isSuccess()) {
                    fjOrder = new FjOrder(fjOrderTo.address, new ArrayList<>(), fjOrderTo.order_no, fjOrderTo.create_time);
                    if (fjOrderTo.order_goods != null)
                        for (int i = 0; i < fjOrderTo.order_goods.length; i++) {
                            FjOrderItemTo item = fjOrderTo.order_goods[i];
                            fjOrder.fjItems.add(new FjOrder.FjItem(fjOrder.fjInfoNo ,fjOrder.createTime, item.id, item.goodsName, SteelardHelp.formatMoneyFloat(item.amount), item.goodsWeight, 0));
                        }
                    
                    FjOrder waitOrder = FjApp.install.getFjWaitOrder().popWaitOrder(fjOrder.fjInfoNo, fjOrder);
                    re.setData(waitOrder == null ? fjOrder : waitOrder);
                }

                if(ree.isSuccess()) {
                    try {
                        JsonP1 jsonP1 = new JsonP1(new JsonParser().parse(json));
                        FjApp.install.getFjInfo().orderCount = jsonP1.get("order_count",true).getAsInt(FjApp.install.getFjInfo().orderCount);
                    }catch (Exception e){}
                }

                complete(re);

            } else {
                ResponEntity<FjOrder> re = ResponEntity.success(fjOrder);
                complete(re);
            }
        }

        @Override
        public void onEnd(boolean isCancel, ResponEntity<FjOrder> result) {
            super.onEnd(isCancel, result);
            ViewUIHelp.disProgressBar(getId());

            if (isCancel) {
                RouterUINavigation.getInstance().dismiss(FjOrderFragment.this);
                return;
            }
            isRealNoFjOrder = false;
            if (result.isSuccess()) {
                AppUIHelp.tryShowTipsSHORT(result.getMsg());
                if (result.getData() == null) {
                    isRealNoFjOrder = true;
                    fjInfo.setCurFj(null, null);
                } else {
                    fjInfo.setCurFj(result.getData(), result.getData().findNext(null));
                }
                FjApp.install.upFjInfo(fjInfo);

            } else {
                new HandleDialog().show(getActivity(), result.getMsg(), OnSteelyardKeyEvent.KEYCODE_9, "重试（按9）", new Runnable() {
                    @Override
                    public void run() {
                        LoadFjOrderTask.this.action();
                        LoadFjOrderTask.this.execTask();
                    }
                }, new Runnable() {
                    @Override
                    public void run() {
                        RouterUINavigation.getInstance().dismiss(FjOrderFragment.this);
                    }
                });
            }
        }
    }

}
